/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-05-29 08:59:27
 * @LastEditors: voanit
 * @LastEditTime: 2022-05-29 16:17:39
 */

import React, { Dispatch, useRef, useState, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { ThunkAction } from 'redux-thunk'
import { RootState } from './store'
// import { } from './store/actions/todo'
import { delTodo, addTodo, changeStateTodo, getTodos } from './store/actions/todo'
import { TodoAction } from './store/actions/todo'

const Todo = () => {
  // const list = useSelector<{ todo: [] }, { id: number, name: string, isDone: boolean }[]>(state => state.todo)
  // const list = useSelector((state: { todo: { id: number, name: string, isDone: boolean }[] }) => state.todo)
  const list = useSelector((state: RootState) => state.todo)
  console.log(list, 555);


  const dispatch = useDispatch()
  // dispatch({
  //   type: 'abc',
  //   payload: 123
  // })

  /* 受控组件写法 */
  const [val, setVal] = useState('')
  const handle = (e: any) => {

    let t = e.target as HTMLInputElement
    // 类型断言
    console.log(t.value, 88);
    setVal(t.value)

  }
  const changeHandle2 = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // refIpt.current.value
    // console.log(e.key === "Enter", 77);
    /* 受控组件写法： */
    if (e.key === "Enter") {
      dispatch(addTodo(val)) // 类型断言
    }
    /* 受控组件写法： */
  }


  /* 非受控组件写法： */
  const refIpt = useRef<HTMLInputElement>(null)
  const changeHandle = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // refIpt.current.value
    // console.log(e.key === "Enter", 77);
    /* 非受控组件写法： */
    if (e.key === "Enter") {
      dispatch(addTodo(refIpt.current!.value)) // 类型断言
    }
    /* 受控组件写法： */
  }

  /* 删除 */
  const del = (id: number) => {
    dispatch(delTodo(id))
  }

  /* 状态更改 */
  // const [chk, setChk] = useState(false)
  const changeChk = (id: number, isDone: boolean) => {
    // console.log(e.target.checked, 8811);
    // let t = e.target as HTMLInputElement
    // // setChk(t.checked)
    dispatch(changeStateTodo(id, isDone))
  }

  /* 初次进入 */
  useEffect(() => {
    dispatch(getTodos())
  }, [])
  return <div>
    御剑乘风来,除魔天地间!Todo
    <hr />
    非受控组件写法：<input type="text" ref={refIpt} onKeyUp={changeHandle} />
    <hr />
    受控组件写法： <input type="text" value={val} onChange={handle} onKeyUp={changeHandle2} />
    <ul>
      {list.map(item => {
        return <li key={item.id}>
          <input type='checkbox' checked={item.isDone} onChange={() => changeChk(item.id, !item.isDone)} />
          {item.name}
          ====<button onClick={() => del(item.id)}>删除</button>
        </li>
      })}

    </ul>
  </div >
};
export default Todo